/**
 * 统一的图数据接口
 * 为不同数据源提供统一的数据访问接口
 */

/**
 * 图数据接口基类
 */
export class GraphDataInterface {
  constructor() {
    this.data = null
    this.isLoaded = false
    this.listeners = []
  }

  /**
   * 加载数据
   */
  async loadData() {
    throw new Error('loadData method must be implemented')
  }

  /**
   * 获取节点数据
   */
  getNodes() {
    throw new Error('getNodes method must be implemented')
  }

  /**
   * 获取边数据
   */
  getEdges() {
    throw new Error('getEdges method must be implemented')
  }

  /**
   * 获取节点类型颜色配置
   */
  getNodeTypeColors() {
    throw new Error('getNodeTypeColors method must be implemented')
  }

  /**
   * 获取边类型样式配置
   */
  getEdgeTypeStyles() {
    throw new Error('getEdgeTypeStyles method must be implemented')
  }

  /**
   * 获取数据统计信息
   */
  getStats() {
    const nodes = this.getNodes()
    const edges = this.getEdges()
    
    return {
      nodeCount: Object.keys(nodes || {}).length,
      edgeCount: Object.keys(edges || {}).reduce((total, key) => {
        return total + (edges[key].data ? edges[key].data.length : 0)
      }, 0),
      nodeTypes: this._getNodeTypes(nodes),
      edgeTypes: this._getEdgeTypes(edges)
    }
  }

  /**
   * 添加数据变化监听器
   */
  addListener(callback) {
    this.listeners.push(callback)
  }

  /**
   * 移除数据变化监听器
   */
  removeListener(callback) {
    const index = this.listeners.indexOf(callback)
    if (index > -1) {
      this.listeners.splice(index, 1)
    }
  }

  /**
   * 通知监听器数据已更新
   */
  notifyListeners() {
    this.listeners.forEach(callback => callback(this))
  }

  /**
   * 获取节点类型统计
   */
  _getNodeTypes(nodes) {
    const types = {}
    Object.values(nodes || {}).forEach(node => {
      const type = node.type || 'default'
      types[type] = (types[type] || 0) + 1
    })
    return types
  }

  /**
   * 获取边类型统计
   */
  _getEdgeTypes(edges) {
    const types = {}
    Object.values(edges || {}).forEach(edgeGroup => {
      if (edgeGroup.data) {
        edgeGroup.data.forEach(edge => {
          const type = edge.type || 'default'
          types[type] = (types[type] || 0) + 1
        })
      }
    })
    return types
  }
}

/**
 * 静态数据接口实现
 */
export class StaticGraphDataInterface extends GraphDataInterface {
  constructor(graphData, nodeTypeColors = {}, edgeTypeStyles = {}) {
    super()
    this.graphData = graphData
    this.nodeTypeColors = nodeTypeColors
    this.edgeTypeStyles = edgeTypeStyles
    this.isLoaded = true
  }

  async loadData() {
    // 静态数据已经加载完成
    this.notifyListeners()
    return this.graphData
  }

  getNodes() {
    return this.graphData?.nodes || {}
  }

  getEdges() {
    return this.graphData?.edges || {}
  }

  getNodeTypeColors() {
    return this.nodeTypeColors
  }

  getEdgeTypeStyles() {
    return this.edgeTypeStyles
  }

  getSettings() {
    return this.graphData?.settings || {}
  }
}

/**
 * API数据接口实现
 */
export class APIGraphDataInterface extends GraphDataInterface {
  constructor(apiEndpoint, nodeTypeColors = {}, edgeTypeStyles = {}) {
    super()
    this.apiEndpoint = apiEndpoint
    this.nodeTypeColors = nodeTypeColors
    this.edgeTypeStyles = edgeTypeStyles
  }

  async loadData() {
    try {
      const response = await fetch(this.apiEndpoint)
      this.data = await response.json()
      this.isLoaded = true
      this.notifyListeners()
      return this.data
    } catch (error) {
      console.error('Failed to load graph data from API:', error)
      throw error
    }
  }

  getNodes() {
    return this.data?.nodes || {}
  }

  getEdges() {
    return this.data?.edges || {}
  }

  getNodeTypeColors() {
    return this.nodeTypeColors
  }

  getEdgeTypeStyles() {
    return this.edgeTypeStyles
  }

  getSettings() {
    return this.data?.settings || {}
  }
}

/**
 * Neo4j数据接口实现
 */
export class Neo4jGraphDataInterface extends GraphDataInterface {
  constructor(neo4jConfig, nodeTypeColors = {}, edgeTypeStyles = {}) {
    super()
    this.neo4jConfig = neo4jConfig
    this.nodeTypeColors = nodeTypeColors
    this.edgeTypeStyles = edgeTypeStyles
  }

  async loadData() {
    try {
      // 这里应该实现Neo4j的连接和查询逻辑
      // 暂时使用模拟数据
      console.log('Loading data from Neo4j...', this.neo4jConfig)
      
      // 模拟异步加载
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 返回模拟的Neo4j数据结构
      this.data = this._generateNeo4jMockData()
      this.isLoaded = true
      this.notifyListeners()
      return this.data
    } catch (error) {
      console.error('Failed to load graph data from Neo4j:', error)
      throw error
    }
  }

  getNodes() {
    return this.data?.nodes || {}
  }

  getEdges() {
    return this.data?.edges || {}
  }

  getNodeTypeColors() {
    return this.nodeTypeColors
  }

  getEdgeTypeStyles() {
    return this.edgeTypeStyles
  }

  getSettings() {
    return this.data?.settings || {}
  }

  /**
   * 生成模拟的Neo4j数据
   */
  _generateNeo4jMockData() {
    return {
      settings: {
        epoch: 'time',
        epochFormat: 'YYYY-MM-DD HH:mm:ss',
        source: 'source',
        target: 'target'
      },
      nodes: {
        '数据库节点1': { type: 'database', group: 1, category: '数据库' },
        '数据库节点2': { type: 'database', group: 1, category: '数据库' },
        '应用节点1': { type: 'application', group: 2, category: '应用' },
        '应用节点2': { type: 'application', group: 2, category: '应用' },
        '用户节点1': { type: 'user', group: 3, category: '用户' },
        '用户节点2': { type: 'user', group: 3, category: '用户' },
        '服务节点1': { type: 'service', group: 4, category: '服务' },
        '服务节点2': { type: 'service', group: 4, category: '服务' }
      },
      edges: {
        'database_connections': {
          data: [
            { source: '数据库节点1', target: '应用节点1', type: 'connects', weight: 2, time: '2024-01-01 10:00:00' },
            { source: '数据库节点2', target: '应用节点2', type: 'connects', weight: 2, time: '2024-01-01 10:30:00' }
          ]
        },
        'user_interactions': {
          data: [
            { source: '用户节点1', target: '应用节点1', type: 'uses', weight: 1, time: '2024-01-01 11:00:00' },
            { source: '用户节点2', target: '应用节点2', type: 'uses', weight: 1, time: '2024-01-01 11:30:00' }
          ]
        },
        'service_calls': {
          data: [
            { source: '应用节点1', target: '服务节点1', type: 'calls', weight: 3, time: '2024-01-01 12:00:00' },
            { source: '应用节点2', target: '服务节点2', type: 'calls', weight: 3, time: '2024-01-01 12:30:00' },
            { source: '服务节点1', target: '服务节点2', type: 'communicates', weight: 2, time: '2024-01-01 13:00:00' }
          ]
        }
      }
    }
  }
}

/**
 * 数据接口工厂
 */
export class GraphDataInterfaceFactory {
  /**
   * 创建数据接口实例
   */
  static create(type, config = {}) {
    switch (type) {
      case 'static':
        return new StaticGraphDataInterface(
          config.data,
          config.nodeTypeColors,
          config.edgeTypeStyles
        )
      
      case 'api':
        return new APIGraphDataInterface(
          config.endpoint,
          config.nodeTypeColors,
          config.edgeTypeStyles
        )
      
      case 'neo4j':
        return new Neo4jGraphDataInterface(
          config.neo4jConfig,
          config.nodeTypeColors,
          config.edgeTypeStyles
        )
      
      default:
        throw new Error(`Unsupported data interface type: ${type}`)
    }
  }

  /**
   * 获取支持的数据接口类型
   */
  static getSupportedTypes() {
    return ['static', 'api', 'neo4j']
  }
}

/**
 * 默认节点类型颜色
 */
export const defaultNodeTypeColors = {
  database: '#ff6b6b',
  application: '#4ecdc4',
  user: '#45b7d1',
  service: '#96ceb4',
  default: '#ffffff'
}

/**
 * 默认边类型样式
 */
export const defaultEdgeTypeStyles = {
  connects: { color: '#74b9ff', width: 2 },
  uses: { color: '#0984e3', width: 1 },
  calls: { color: '#6c5ce7', width: 3 },
  communicates: { color: '#00b894', width: 2 },
  default: { color: '#ddd', width: 1 }
}








